package com.cloudpivot.project.crmprojectnew.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.cloudpivot.project.crmprojectnew.configuration.CrmConfig;
import com.cloudpivot.project.crmprojectnew.pojo.Systemusers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.cloudpivot.project.crmprojectnew.util.CrmNormalUtil.encodeCrmUrl;
import static com.cloudpivot.project.crmprojectnew.util.CrmNormalUtil.getCrmDomainname;

/**
 * eMail
 * 获取crm用户guid
 */
@Service
@Slf4j
public class SystemusersService {
    @Autowired
    private HttpAPIServiceForCrm httpAPIServiceForCrm;
    @Autowired
    private CrmConfig crmConfig;
    @Autowired
    private ObjectMapper objectMapper;

    public String getCrmUserGuid(String email) {
        //获取domainname
        String domainName = getCrmDomainname(email);
        if (domainName == null) {
            return null;
        }
        //拼接url
        String url = String.format("%ssystemusers?$filter=domainname eq '%s'", this.crmConfig.getCrmurl(), domainName);
        url=encodeCrmUrl(url);
        try {
            //请求guid
            String responseStr = this.httpAPIServiceForCrm.doGetCrm(url);
            Systemusers systemusers = objectMapper.readValue(responseStr, Systemusers.class);
            if (systemusers.getValue().isEmpty()) {
                return null;
            } else {
                return systemusers.getValue().get(0).getSystemuserid();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }


    }

}
